from typing import Any, Dict, List, TextIO

from elasticsearch import Elasticsearch
import re
from networkit import *

import sys
sys.path.append("../workflow4threeman")
from workflow.Configuration import DataBaseConfig
from workflow.NetPayLoad import NetPayLoad
from workflow.DataExtractor.es_extractor import ElasticSearchConfig,ElasticSearchDataExtractor

class net_constructor:
    def __init__(self,time_range:list=None,sensitive_word:List[str]=None,) -> None:
        self.ESD = ElasticSearchDataExtractor(ElasticSearchConfig)
        self.time_range =  time_range
        self.sensitive_word = sensitive_word
    
    def construction(self,) -> graph.Graph():
        NP = self.ESD.get_flowtext()
        user_graph = graph.Graph()
        root_uid = 1840483562
        graph_id_list = list()
        graph_id_list.append(root_uid)
        #for demo root u_id = 1840483562
        for flow_text in NP.raw_flowtext:

            if "//@" not in flow_text['_source']['text']:
                follow_id = int(flow_text['_source']['uid'])
                if follow_id not in graph_id_list:
                    graph_id_list.append(follow_id)
                user_graph.addEdge(graph_id_list.index(root_uid),graph_id_list.index(follow_id),addMissing=True)
            else:
                follow_id_list = self.get_user_id(flow_text)
                sec_user_id = follow_id_list[0]
                if sec_user_id not in graph_id_list:
                    graph_id_list.append(sec_user_id)
                
                for f in follow_id_list:
                    if f not in graph_id_list:
                        graph_id_list.append(f)
                
                user_graph.addEdge(graph_id_list.index(root_uid),graph_id_list.index(sec_user_id),addMissing=True)
                for i in range(1,len(follow_id_list)):
                    user_graph.addEdge(graph_id_list.index(sec_user_id),graph_id_list.index(follow_id_list[i]),addMissing=True)
                    sec_user_id = follow_id_list[i]

        return user_graph
    
    def get_user_id(self,flow_text:dict,)->List[int]:
        #TODO 可能存在重复添加边的问题
        user_id_list = list()
        uname_list = list()

        user_id_list.append(flow_text['_source']['uid'])
        chain_text = flow_text['_source']['text']
        chain_text = chain_text.split("//@")
        chain_text = chain_text[1:]
        for c in chain_text:
            index = c.index(':')
            uname_list.append(c[:index])

        for uname in uname_list:
            user_id_list.append(self.ESD.get_uid(uname))
        
        #按实际转发顺序反序排列
        user_id_list.reverse()
        
        return user_id_list
